<!-- 首页 -->
<template>
	<view class="container">
		<view class="grid">
			<view class="grid-item" v-for="(item,index) in tagList" :key="index" @click="handleSelectTag(item)"
				:class="{'grid-item-active':checkSelection(item)}">
				<text>{{item}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		protocolList
	} from "@/api/mine/auth.js"
	export default {
		name: "",
		props: ["value"],
		data() {
			return {
				tagList: [],
				selection: []
			}
		},
		watch: {
			value: {
				immediate: true,
				async handler(value) {
					if (!this.tagList.length) await this.getList()
					if (value) {
						// 将 value 按逗号拆分为数组
						const values = value.split(',');
						if (values.length) {
							let index = this.tagList.indexOf(values[0])
							if (index === -1) {
								this.selection = []
							} else {
								this.selection = values
							}
						} else {
							this.selection = []
						}
					}
				}
			}
		},
		methods: {
			async getList() {
				await protocolList().then(res => {
					let {
						data
					} = res
					this.tagList = data[1]['children'].map(item => item.title)
				})
			},
			checkSelection(val) {
				return this.selection.indexOf(val) !== -1
			},
			handleSelectTag(val) {
				let index = this.selection.indexOf(val)
				if (index !== -1) {
					this.selection.splice(index, 1)
				} else {
					this.selection.push(val)
				}
				this.$emit('change', this.selection)
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		.grid {
			display: flex;
			flex-wrap: wrap;
			padding: 32rpx 0 62rpx 0;

			.grid-item {
				background-color: #F0F1F2;
				border-radius: 8rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-weight: 400;
				font-size: 24rpx;
				padding: 16rpx 52rpx;
				margin-right: 26rpx;
			}

			.grid-item-active {
				background-color: #FE3F59;
				color: #fff;
			}
		}

		::v-deep .van-index-anchor {
			padding: 0;
		}
	}
</style>